<?php
//公用函数库

/**
 * 判断是否为手机浏览器
 */
function is_mobile(){
    //匹配的手机型号
    $regex_match="/(nokia|iphone|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|";
    $regex_match.="htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|";
    $regex_match.="blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|";
    $regex_match.="symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|";
    $regex_match.="jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220";
    $regex_match.=")/i";
	if( isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT'])) ){
		return true;
	}
	if( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !==false ){
		//兼容微信内置浏览器，PC访问
		if(  strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !==false or strpos($_SERVER['HTTP_USER_AGENT'], 'Win') !==false ){
			return false;
		}
		return true;
	}
    return false;
}

/**
 * sn生成
 * @param null $code
 * @return string
 */
function create_sn($code = null){
    switch (strtolower($code)) {
        case 'clues':
            $sn = '1' . date('ymdHis').rand(10000,99999).rand(10000,99999);
            break;
        default:
            $sn = 'D' . date('ymdHis').rand(10000,99999).rand(10000,99999);
            break;
    }
    return $sn;
}

function HmacMd5($data,$key)
{
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC
// Hacked by Lance Rushing(NOTE: Hacked means written)

//需要配置环境支持iconv，否则中文参数不能正常处理
$key = iconv("GB2312","UTF-8",$key);
$data = iconv("GB2312","UTF-8",$data);

$b = 64; // byte length for md5
if (strlen($key) > $b) {
$key = pack("H*",md5($key));
}
$key = str_pad($key, $b, chr(0x00));
$ipad = str_pad('', $b, chr(0x36));
$opad = str_pad('', $b, chr(0x5c));
$k_ipad = $key ^ $ipad ;
$k_opad = $key ^ $opad;

return md5($k_opad . pack("H*",md5($k_ipad . $data)));
}

/**
 +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 +----------------------------------------------------------
 * @static
 * @access public
 +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function msubstr($str, $start = 0, $length, $suffix = false, $charset = "utf-8") {
	if (function_exists("mb_substr")) {
		if ($suffix && strlen($str) > $length)
			return mb_substr($str, $start, $length, $charset) . $suffix;
		else
			return mb_substr($str, $start, $length, $charset);
	}
	elseif (function_exists('iconv_substr')) {
		if ($suffix && strlen($str) > $length)
			return iconv_substr($str, $start, $length, $charset) . $suffix;
		else
			return iconv_substr($str, $start, $length, $charset);
	}
	$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$slice = join("", array_slice($match[0], $start, $length));
	if ($suffix)
		return $slice . $suffix;
	return $slice;
}

/**
 * MD5方式签名
 * @param $okey
 * @param $odata
 * @return string
 */
function MD5sign($okey,$odata)
{
	 $signdata=hmac("",$odata);			     
	 return hmac($okey,$signdata);
}

/**
 * @param $key
 * @param $data
 * @return string
 */
function hmac ($key, $data)
{
  $key = iconv('gb2312', 'utf-8', $key);
  $data = iconv('gb2312', 'utf-8', $data);
  $b = 64;
  if (strlen($key) > $b) {
  $key = pack("H*",md5($key));
  }
  $key = str_pad($key, $b, chr(0x00));
  $ipad = str_pad('', $b, chr(0x36));
  $opad = str_pad('', $b, chr(0x5c));
  $k_ipad = $key ^ $ipad ;
  $k_opad = $key ^ $opad;
 return md5($k_opad . pack("H*",md5($k_ipad . $data)));
} 

/*
 功能 把http请求返回数组 格式化成数组
*/
function parseRecv($source)
{
	$ret = array();
	$temp = explode("&",$source);
	foreach ($temp as $value) {
		$index=strpos($value,"=");
		$_key=substr($value,0,$index);
		$_value=substr($value,$index+1);
		$ret[$_key] = $_value;
	}
	return $ret;
}

//返回URL处理
function parseUrl($payUrl)
{
	$temp =explode("<hi:$$>",$payUrl);			
	$url_lst=explode("<hi:=>",$temp[0]);
	$url=$url_lst[1];
	$method_lst=explode("<hi:=>",$temp[1]);
	$method=$method_lst[1];
	$sessionid_lst=explode("<hi:=>",$temp[2]);
	$sessionid=$sessionid_lst[1];
	$url=$url."?SESSIONID=".$sessionid;
	$rpayUrl = array();		
	$rpayUrl["url"]=$url;
	$rpayUrl["method"]=$method;
	return $rpayUrl;
}

/**
 * 姓名加密，首**尾
 * @param string $username
 * @return string
 */
function hideusername($username='')
{
	$length = mb_strlen($username,'UTF8');
	if($length<=1){
		return '*'; 
	}elseif($length==2){
		return msubstr($username,0,1,'**');
	}else{
		return msubstr($username,0,1,'**').msubstr($username,-1,1);
	}
}

//前台：通过memberId生成邀请码
function mem_pop_uri($mid){
    if(empty($mid)){
        return false;
    }
    $code = 1000000 + 2017 + $mid;
    return $code;
}


//前台：通过邀请码得到memberid
function getMemIdByInviteCode($code){
    $mid = $code - 1000000 - 2017;
    return $mid;
}

/*判断访问客户端类型*/
function get_device_type(){
	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$type = 'other';
	if(strpos($agent, 'iphone') || strpos($agent, 'ipad')){
		$type = 'ios';
	}
	if(strpos($agent, 'android')){
		$type = 'android';
	}
	return $type;	
}

/**
 * 除去数组中的空值和签名参数
 * @param $para 签名参数组
 * return 去掉空值与签名参数后的新签名参数组
 */
function paraFilter($para) {
	$para_filter = array();
	while (list ($key, $val) = each ($para)) {
		if($key == "sign" || $val == "")continue;
		else	$para_filter[$key] = $para[$key];
	}
	return $para_filter;
}
/**
 * 对数组排序
 * @param $para 排序前的数组
 * return 排序后的数组
 */
function argSort($para) {
	ksort($para);
	reset($para);
	return $para;
}
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstring($para) {
	$arg  = "";
	while (list ($key, $val) = each ($para)) {
		$arg.=$key."=".$val."&";
	}
	//去掉最后一个&字符
	$arg = substr($arg,0,count($arg)-2);
	//file_put_contents("log.txt","转义前:".$arg."\n", FILE_APPEND);
	//如果存在转义字符，那么去掉转义
	if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
	//file_put_contents("log.txt","转义后:".$arg."\n", FILE_APPEND);
	return $arg;
}
function format_time($atime,$format=''){
	$time_diff = time()-$atime;
	if($time_diff<60){
		$time = "1分钟前";
	}elseif($time_diff>60 && $time_diff<3600){
		$time = floor($time_diff/60)."分钟前";
	}elseif($time_diff>3600 && $time_diff<3600*24){
		$time = floor($time_diff/3600)."小时前";
	}elseif($time_diff>3600*24 && $time_diff<3600*24*3){
		$time = floor($time_diff/(3600*24))."天前";
	}else{
		$time = $format ? date($format,$atime) : date('Y-m-d',$atime);
	}
	return $time;
}
function showbytime($val){
    if($val<=3600){
        $str = ceil($val/60).'分钟前';
    }else if($val>3600 && $val<3600*24){
        $str = ceil($val/60/60).'小时前';
    }else {
        $str = ceil($val/60/60/24).'天前';
    }
    return $str; 
}

/**
 * 主库连接数据库模型
 * @param string $table
 */
function _M($table=''){
    static $db_id = 0;
    if($db_id==0){
        $db = M($table, '', C('DB_DSN_WRITE'))->db(1, C('DB_DSN_WRITE'));
        $db_id = 1;
    } else {
        $db = M($table, '', C('DB_DSN_WRITE'))->db($db_id);
    }

    return $db;
}

/**
  +----------------------------------------------------------
  * Service函数用于实例化一个服务层的Service
  +----------------------------------------------------------
  * @param string name Service名称[区分大小写]
  +----------------------------------------------------------
  * @return Service对像
  +----------------------------------------------------------
 */
function Service($name='') {
    static $_service = array();
    
    $service_name = empty($name) ? 'Default' : $name;
    if(isset($_service[$service_name])) return $_service[$service_name];
    
    $class = $service_name . 'Service';
    $service_path = LIB_PATH . 'Service/';
    
    import('BaseService', $service_path);
    import($class, $service_path);
    $_service[$service_name] = new $class();
    
    return $_service[$service_name];
}

/**
 * 判断是否是post请求
 * @return true/false 是/否
 */
function is_post(){
    if($_SERVER['REQUEST_METHOD'] == 'POST'){
        return true;
    } else {
        return false;
    }
}
/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 * @param string $day1
 * @param string $day2
 * @return number
 */
function _diffBetweenTwoDays($day1, $day2)
{
	$day1 = mb_substr($day1 , 0 , 10);
	$day2 = mb_substr($day2 , 0 , 10);
	$second1 = strtotime($day1);
	$second2 = strtotime($day2);
	if($second1 < $second2)
	{
		$tmp = $second2;
		$second2 = $second1;
		$second1 = $tmp;
	}
	return ($second1 - $second2) / 86400;
}

?>
